#!/bin/sh

# Init file for rustodon
#
# description: A Mastodon-compatible, ActivityPub-speaking server in Rust

### BEGIN INIT INFO
# Provides:          rustodon
# Required-Start:    $all
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: rustodon
# Description:       A Mastodon-compatible, ActivityPub-speaking server in Rust
### END INIT INFO


# Quick start-stop-daemon example, derived from Debian /etc/init.d/ssh
set -e

# Must be a valid filename
NAME=rustodon
# This will store the process id of any running service
PIDFILE=/var/run/$NAME.pid
#This is the command to be run, give the full pathname
DAEMON_CWD=/srv/rustodon
# This is the program that invokes the service
DAEMON="/srv/rustodon/target/release/rustodon"
# These are commandline args. They should reflect your environment needs.
DAEMON_OPTS="run"

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

case "$1" in
  start)
	echo -n "Starting daemon: "$NAME
	# -m creates the pidfile becaus AFAICT Rustodon cannot do that itself
	# -b forces the program into the background because Rustodon doesn't automatically do that.
	# /usr/bin/env is used to set the environment variable Rocket needs to set an environment
	start-stop-daemon -m -b --start --quiet --pidfile $PIDFILE --chdir $DAEMON_CWD --exec /usr/bin/env ROCKET_ENV=staging $DAEMON -- $DAEMON_OPTS
        echo "."
	;;
  stop)
        echo -n "Stopping daemon: "$NAME
	start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
        echo "."
	;;
  restart)
        echo -n "Restarting daemon: "$NAME
	start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $PIDFILE
	start-stop-daemon -m -b --start --quiet --pidfile $PIDFILE --chdir $DAEMON_CWD --exec /usr/bin/env ROCKET_ENV=staging $DAEMON -- $DAEMON_OPTS
	echo "."
	;;

  *)
	echo "Usage: "$0" {start|stop|restart}"
	exit 1
esac

exit 0
